package com.zwf.checkstyledemo1.checks;

import com.puppycrawl.tools.checkstyle.api.*;

import java.io.File;
import java.util.regex.Pattern;

public class CommentRatioCheck extends AbstractFileSetCheck  {

    int x = 1, y = 0;

    // 默认最小注释率 (0%)
    private double minCommentRatio = 0.3;

    // 用于统计的变量
    private int totalLines;
    private int commentLines;
    private boolean inBlockComment;

    // 正则匹配注释
    private static final Pattern BLOCK_COMMENT_START = Pattern.compile("/\\*");
    private static final Pattern BLOCK_COMMENT_END = Pattern.compile("\\*/");
    private static final Pattern LINE_COMMENT = Pattern.compile("//");
    private static final Pattern CODE_LINE = Pattern.compile("\\S+");


    @Override
    protected void processFiltered(File file, FileText fileText) throws CheckstyleException {
        totalLines = 0;
        commentLines = 0;
        String[] lines = fileText.toLinesArray();
        for (String line : lines) {
            totalLines++;
            analyzeLine(line.trim());
        }

        double ratio = totalLines > 0 ? (double) commentLines / totalLines : 0.0;
        if (ratio < minCommentRatio) {
            // 使用 FileSetCheck 的日志方法
            log(1, "注释率不足: {0}% (要求: {1}%);总行数={2};注释行={3}",
                    (int)(ratio * 100),
                    (int)(minCommentRatio * 100),
                    totalLines,
                    commentLines);
        }
    }


    private void analyzeLine(String line) {
        if (line.isEmpty()) return;

        if (inBlockComment) {
            commentLines++;
            if (BLOCK_COMMENT_END.matcher(line).find()) {
                inBlockComment = false;
            }
            return;
        }

        if (BLOCK_COMMENT_START.matcher(line).find()) {
            commentLines++;
            if (!BLOCK_COMMENT_END.matcher(line).find()) {
                inBlockComment = true;
            }
            return;
        }

        if (LINE_COMMENT.matcher(line).find()) {
            commentLines++;
            return;
        }

        // 检查是否是代码行
        if (CODE_LINE.matcher(line).find() &&
                !line.startsWith("package") &&
                !line.startsWith("import")) {
            // 这是代码行，不增加注释计数
        }
    }

    public void setMinCommentRatio(double minCommentRatio) {
        this.minCommentRatio = minCommentRatio;
    }
}
